<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户">
                <a-input v-model="queryParam.username" placeholder=""/>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
              <a-form-item label="内容">
                <a-input v-model="queryParam.send_content" placeholder=""/>
              </a-form-item>
            </a-col>

            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <!-- 1:待受理2:处理中3:待审核4:已完成 -->
                  <a-select v-model="queryParam.status" placeholder="请选择">
                    <a-select-option value="1">待受理</a-select-option>
                    <a-select-option value="2">处理中</a-select-option>
                    <a-select-option value="3">待审核</a-select-option>
                    <a-select-option value="4">已完成</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <!-- <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
            <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown> -->
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="send_content" slot-scope="text">
          <ellipsis :length="10" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>

        <span slot="sendImg" slot-scope="text">
          <viewer>
            <div class="table-img-wrap">
              <div v-for="itemImg in text" :key="itemImg.id">
                <img :src="itemImg.host + itemImg.img_url" />
              </div>
            </div>
          </viewer>
        </span>

        <span slot="finish_time" slot-scope="text">
          {{ text ? new Date(text * 1000).toLocaleDateString() : '' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a-dropdown>
              <a-menu slot="overlay">
                <!-- 1:待受理2:处理中3:待审核4:已完成 -->
                <a-menu-item><a @click="onChangeStatus(record,1)">待受理</a></a-menu-item>
                <a-menu-item><a @click="onChangeStatus(record,2)">处理中</a></a-menu-item>
                <a-menu-item><a @click="onChangeStatus(record,3)">待审核</a></a-menu-item>
                <a-menu-item><a @click="onChangeStatus(record,4)">已完成</a></a-menu-item>
              </a-menu>
              <a>修改状态<a-icon type="down"/></a>
            </a-dropdown>
            <a-divider type="vertical" />
            <a @click="handleBackDetails(record)">回复</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />

      <back-content
        :visible="visibleBack"
        :model="mdlBack"
        @cancel="handleBackModal"
        @ok="handleBackModal"
      />
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { query, add, changeStatus, del } from '@/api/task'

// import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './components/CreateForm'
import BackContent from './components/BackContent.vue'

const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '用户',
    dataIndex: 'user.username'
  },
  {
    title: '内容',
    dataIndex: 'send_content',
    scopedSlots: { customRender: 'send_content' }
  },
  {
    title: '图片',
    dataIndex: 'sendImg',
    scopedSlots: { customRender: 'sendImg' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'create_time'
  },
  {
    title: '完成时间',
    dataIndex: 'finish_time',
    scopedSlots: { customRender: 'finish_time' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

// 1:待受理2:处理中3:待审核4:已完成
const statusMap = {
  1: {
    status: 'default',
    text: '待受理'
  },
  2: {
    status: 'processing',
    text: '处理中'
  },
  3: {
    status: 'warning',
    text: '待审核'
  },
  4: {
    status: 'success',
    text: '已完成'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    BackContent
    // StepByStepModal
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return query(requestParameters)
          .then(res => {
            return res.result
          }).catch(errors => {
            console.log(errors)
          })
      },
      visibleBack: false,
      mdlBack: null
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
  },
  computed: {
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
          //   new Promise((resolve, reject) => {
          //     setTimeout(() => {
          //       resolve()
          //     }, 1000)
          //   }).then(res => {
          //     this.visible = false
          //     this.confirmLoading = false
          //     // 重置表单数据
          //     form.resetFields()
          //     // 刷新表格
          //     this.$refs.table.refresh()

          //     this.$message.info('修改成功')
          //   })
          } else {
            // 新增
            add(values).then(res => {
              console.log(res)
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).catch(errors => {
              console.log(errors)
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onChangeStatus (record, status) {
      console.log(record, status)
      // 1:待受理2:处理中3:待审核4:已完成
      const map = {
        1: '待受理', 2: '处理中', 3: '待审核', 4: '已完成'
      }
      changeStatus({ id: record.id, status }).then(res => {
        console.log(res)
        // 刷新表格
        this.$refs.table.refresh()
        this.$message.success(`已修改为${map[status]}`)
      })
    },
    handleDel (record) {
      const _that = this
      this.$confirm({
        title: '请确认要删除任务？',
        content: h => <div style="color:red;">正在删除“{ record.content }”</div>,
        icon: h => <a-icon style="color:red;" type="delete" />,
        onOk () {
          del({ id: record.id }).then(res => {
            // console.log(res)
            _that.$message.success('删除成功')
            // 刷新表格
            _that.$refs.table.refresh()
          }).catch(errors => {
            console.log(errors)
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    handleBackDetails (record) {
      // console.log(record)
      if (record.status >= 3) {
        this.visibleBack = true
        this.mdlBack = record
      } else {
        this.$message.info('请等待处理后再打开')
      }
    },
    handleBackModal () {
      this.visibleBack = false
    }
  }
}
</script>

<style scoped>
.table-img-wrap {
  display: flex;
  width: 200px;
  overflow: auto;
}
.table-img-wrap > div {
  margin: 0 10px 0 0;
}
.table-img-wrap img {
  width: 40px;
  height: 40px;
}
</style>
